//
//  JobDetailViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/20.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "JobDetailViewController.h"
#import "JobCell.h"
#import "JobDetailBaseInfoView.h"
#import "CompanyJobModel.h"
#import "HRJobDetailViewController.h"
#import "CompanyDetailViewController.h"

#import "PersonalHomeViewController.h"
#import "TransitionToListVC.h"

@interface JobDetailViewController ()<UITableViewDelegate, UITableViewDataSource, JobDetailBaseInfoViewDelegate, ShareViewDelegate, UINavigationControllerDelegate>
{
    NSMutableArray *itemDataArray;
    
    JobDetailBaseInfoView *headerView;
    UIBarButtonItem *collect;
    UIBarButtonItem *share;
    
    ShareView *shareBgView;
}
@property (nonatomic, strong) CompanyJobModel *infoModel;
@property (nonatomic, strong) UIPercentDrivenInteractiveTransition *interactivePopTransition;
@end

@implementation JobDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
//    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.delegate = self;
    
//    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    if (self.navigationController.delegate == self) {
//        self.navigationController.delegate = nil;
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"职位详情";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    // 返回手势
//    UIPanGestureRecognizer *popRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePopRecognizer:)];
//    [self.view addGestureRecognizer:popRecognizer];
    
    if (!self.bgColor) {
        self.bgColor = THEMECOLOR_OF_ORANGE;
    }
    
    itemDataArray = [NSMutableArray arrayWithCapacity:0];
    [self loadData];
}
- (void)loadData {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:self.id forKey:@"job_id"];
    
    [BaseNetManager requestWithMethod:POST path:PersonJobsDeatil_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            self.infoModel = [[CompanyJobModel alloc] init];
            [self.infoModel setValuesForKeysWithDictionary:data];
            self->headerView = [[JobDetailBaseInfoView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, self.infoModel.allHeight) target:self info:self.infoModel showRightIcon:YES topBgColor:self.bgColor];
            [self loadDataJobs];
            [self initUI];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
        [self loadData];
    }];
}
- (void)loadDataJobs {
    self.noDataView.hidden = YES;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:self.id forKey:@"job_id"];
    [dic setObject:PageSize forKey:@"number"];
    
    [BaseNetManager requestWithMethod:POST path:PersonJobs_Relation_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            for (NSDictionary *dic in data) {
                CompanyJobModel *model = [[CompanyJobModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self->itemDataArray addObject:model];
            }
            [self.jobTableView reloadData];
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
//        SVPHUDError(NetErrorAlertText);
        SVPHUDDismiss;
        [self.noDataView vcNilStatusType:VCNilStatusTypeOfNoNet superView:self.view];
    }];
}
- (void)initUI {
    collect = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:(([self.infoModel.favorite_status integerValue])?@"collect_icon_s":@"collect_icon")] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(collectTap)];
    share = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"share_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(shareTap)];
    self.navigationItem.rightBarButtonItems = @[share, collect];
//    self.navigationItem.rightBarButtonItem = collect;
    
    self.jobTableView = [UIToolsControl initTableViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfStatusBarAndNavigationBar-SIMEmojKeyBoardkBottomNOSafeArea_Height-55*Scale) target:self style:UITableViewStyleGrouped];
    self.jobTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.jobTableView.rowHeight = 85*Scale;
    self.jobTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.jobTableView];
    
    UIButton *chatBtn = [UIToolsControl initButtonWithFrame:CGRectMake(LeftSpace, EndY(self.jobTableView)+5*Scale, WIDTH-30*Scale, 45*Scale) imageName:nil target:self action:@selector(chatBtnTap) title:@"立即沟通" titleColor:COLOR_OF_WHITE];
    chatBtn.layer.cornerRadius = 2*Scale;
    chatBtn.layer.masksToBounds = YES;
    chatBtn.backgroundColor = self.bgColor;
    [self.view addSubview:chatBtn];
    
    shareBgView = [[ShareView alloc] initWithTarget:self];
    shareBgView.hidden = YES;
}
- (void)chatBtnTap {
    if (Signin) {
        [self pushChatVC];
    } else {
//        __weak __typeof(self)weakSelf = self;
        [UIToolsControl presentSignin:self callBack:^(BOOL signinFlag) {
//            __strong __typeof(weakSelf)strongSelf = weakSelf;
//            [strongSelf pushChatVC];
        }];
    }
}
- (void)pushChatVC {
//    if ([[TIMManager sharedInstance] getLoginStatus] != TIM_STATUS_LOGINED) {
//        SVPHUDError(@"");
//    }
    TConversationCellData *data = [[TConversationCellData alloc] init];
    data.convId = self.infoModel.hrInfoModel.userid;
    data.btpin_user_id = self.infoModel.hrInfoModel.userid;
    data.convType = TConv_Type_C2C;
    data.title = self.infoModel.hrInfoModel.name;
    data.head = self.infoModel.hrInfoModel.avatar;
    ChatViewController *chat = [[ChatViewController alloc] init];
    chat.isNotice = NO;
    chat.isSessionPush = NO;
    chat.conversation = data;
    chat.job_id = self.id;
    chat.job_cn = @"";
    chat.wage_cn = @"";
    chat.user_name = self.infoModel.hrInfoModel.name;
    [self.navigationController pushViewController:chat animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return itemDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JobCell *cell = [tableView dequeueReusableCellWithIdentifier:isCellID];
    if (!cell) {
        cell = [[JobCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:isCellID];
    }
    CompanyJobModel *model = itemDataArray[indexPath.row];
    [cell reloadDataModel:model];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return JobCellHeight;
}
#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CompanyJobModel *model = itemDataArray[indexPath.row];
    JobDetailViewController *JDVC = [[JobDetailViewController alloc] init];
    JDVC.id = model.id;
    [self.navigationController pushViewController:JDVC animated:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return self.infoModel.allHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00001;
}
- (void)collectTap {
    if (Signin) {
        NSLog(@"collectTap");
        NSString *url = PersonFavoriteJob_URL;
        if ([self.infoModel.favorite_status integerValue]) { // 已关注
            url = Person_CancelFavoriteJob_URL;
        } else { // 未关注
            url = PersonFavoriteJob_URL;
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
        dic = [UIToolsControl getPublicParameter];
        [dic setObject:self.id forKey:@"job_id"];
        
        [BaseNetManager requestWithMethod:POST path:url params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
            if ([responseObject[@"code"] integerValue] == 2000) {
                SVPHUDSuccess(responseObject[@"msg"]);
                if ([self.infoModel.favorite_status integerValue]) {
                    self.infoModel.favorite_status = @"0";
                } else {
                    self.infoModel.favorite_status = @"1";
                }
                self->collect = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:(([self.infoModel.favorite_status integerValue])?@"collect_icon_s":@"collect_icon")] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(collectTap)];
                self.navigationItem.rightBarButtonItems = @[self->share, self->collect];
//                self.navigationItem.rightBarButtonItem = self->collect;
            } else {
                SVPHUDError(responseObject[@"msg"]);
            }
        } failurBlock:^(NSError * _Nonnull error) {
            SVPHUDError(NetErrorAlertText);
        }];
    } else {
        [UIToolsControl presentSignin:self callBack:^(BOOL signinFlag) {
            
        }];
    }
}
- (void)shareTap {
    NSLog(@"shareTap");
    if ([UIToolsControl canOpenWXApp]) {
        shareBgView.hidden = NO;
    } else {
        SVPHUDError(@"请先安装微信App");
    }
}
- (void)shareViewCancel:(ShareView *)shareView {
    shareView.hidden = YES;
}
- (void)shareViewSelectItem:(ShareView *)shareView type:(ShareType)shareType {
    shareView.hidden = YES;
    headerView.shareBgImgView.hidden = NO;
    switch (shareType) {
        case ShareTypeOfWXHaoyou: {
            [UIToolsControl wxShareImg:[UIToolsControl snapshot:headerView.shareBgView] shareType:ShareTypeOfWXHaoyou];
        } break;
        case ShareTypeOfWXPengyouquan: {
            [UIToolsControl wxShareImg:[UIToolsControl snapshot:headerView.shareBgView] shareType:ShareTypeOfWXPengyouquan];
        } break;
        case ShareTypeOfQQ: {
            [UIToolsControl qqShareImg:[UIToolsControl snapshot:headerView.shareBgView] title:@"" desc:@"" shareType:ShareTypeOfQQ];
        } break;
        case ShareTypeOfQQZone: {
            [UIToolsControl qqShareImg:[UIToolsControl snapshot:headerView.shareBgView] title:@"" desc:@"" shareType:ShareTypeOfQQZone];
        } break;
        default:
            break;
    }
    /*
    switch (shareType) {
        case ShareTypeOfWXHaoyou: {
            [UIToolsControl wxShareWebURL:self.infoModel.share_promote_url title:self.infoModel.title desc:[NSString stringWithFormat:@"职位描述：%@", self.infoModel.contents] thumbUrl:nil shareType:ShareTypeOfWXHaoyou];
        } break;
        case ShareTypeOfWXPengyouquan: {
            [UIToolsControl wxShareWebURL:self.infoModel.share_promote_url title:self.infoModel.title desc:[NSString stringWithFormat:@"职位描述：%@", self.infoModel.contents] thumbUrl:nil shareType:ShareTypeOfWXPengyouquan];
        } break;
        case ShareTypeOfQQ: {
            [UIToolsControl qqShareWebURL:self.infoModel.share_promote_url title:self.infoModel.title desc:[NSString stringWithFormat:@"职位描述：%@", self.infoModel.contents] thumbUrl:nil shareType:ShareTypeOfQQ];
        } break;
        case ShareTypeOfQQZone: {
            [UIToolsControl qqShareWebURL:self.infoModel.share_promote_url title:self.infoModel.title desc:[NSString stringWithFormat:@"职位描述：%@", self.infoModel.contents] thumbUrl:nil shareType:ShareTypeOfQQZone];
        } break;
        default:
            break;
    }
    */
    headerView.shareBgImgView.hidden = YES;
}
- (void)jobDetailBaseInfoViewOfHRTap {
    NSLog(@"HRHRHR");
    HRJobDetailViewController *HJDVC = [[HRJobDetailViewController alloc] init];
    HJDVC.infoModel = [self.infoModel copy];
    [self.navigationController pushViewController:HJDVC animated:YES];
}
- (void)jobDetailBaseInfoViewOfCompanyDetailTap {
    NSLog(@"CompanyDetail");
    CompanyDetailViewController *CDVC = [[CompanyDetailViewController alloc] init];
    CDVC.id = self.infoModel.companyInfoModel.id;
    [self.navigationController pushViewController:CDVC animated:YES];
}
- (void)jobDetailBaseInfoViewOfCompanyAddressTap {
    NSLog(@"CompanyAddress");
}

#pragma mark UINavigationControllerDelegate methods
//- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {
//    if ([fromVC isKindOfClass:[JobDetailViewController class]] && [toVC isKindOfClass:[PersonalHomeViewController class]]) {
//        TransitionToListVC *transitionVC = [[TransitionToListVC alloc] init];
//        return transitionVC;
//    } else {
//        return nil;
//    }
//}
- (void)customBackButtonTap {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark UIGestureRecognizer handlers
- (void)handlePopRecognizer:(UIScreenEdgePanGestureRecognizer*)recognizer {
    CGFloat progress = [recognizer translationInView:self.view].x / (self.view.bounds.size.width * 1.0);
    progress = MIN(1.0, MAX(0.0, progress));
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.interactivePopTransition = [[UIPercentDrivenInteractiveTransition alloc] init];
        [self.navigationController popViewControllerAnimated:YES];
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        [self.interactivePopTransition updateInteractiveTransition:progress];
    } else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) {
        if (progress > 0.5) {
            [self.interactivePopTransition finishInteractiveTransition];
        } else {
            [self.interactivePopTransition cancelInteractiveTransition];
        }
        self.interactivePopTransition = nil;
    }
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    CGPoint velocity = [(UIPanGestureRecognizer *)gestureRecognizer velocityInView:self.view];
    CGPoint location = [gestureRecognizer locationInView:self.view];
    if (velocity.x > 0.0f&&(int)location.x%(int)[UIScreen mainScreen].bounds.size.width<60) {
        return NO;
    }
    return YES;
}

@end
